package com.woniuxy.redis.lock.service;

import com.woniuxy.redis.lock.entity.Stu;
import com.woniuxy.redis.lock.mapper.StuMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * description: SecondService <br>
 * date: 2022/1/8 11:53 上午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */
@Service
public class SecondService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    StuMapper stuMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 初始化秒杀商品
     */
    public void start() {
        ListOperations<String, Object> opsForList = redisTemplate.opsForList();
        for (int i = 1; i <= 1000; i++) {
            opsForList.leftPush("list", i);
        }
    }

    //秒杀

    public void second() {
        ListOperations<String, Object> opsForList = redisTemplate.opsForList();
        Object item = opsForList.rightPop("list");
        if (item == null) {
            System.out.println("over");
        } else {
            //添加订单
            int sid = Integer.parseInt(item.toString());
            //将要添加到数据库的对象，发送搭配消息队列中
            //stuMapper.insertStu(new Stu(sid, "name:" + sid, sid, new Date()));
            // 创建对象，把消息扔到队列中
            Stu stu = new Stu(sid, "name:" + sid, sid, new Date());
            rabbitTemplate.convertAndSend("exchangeadd", "add", stu);
            System.out.println("ok:" + item);
        }
    }
}
